﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Cashier_Service;
using Cashier.utils;
using Cashier_Utils;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using Cashier.prints;

namespace Cashier.report
{
    public partial class PurchaseReportControl : UserControl
    {
        private MainForm mainform;
        private static PurchaseReportControl purchaseReportControl;
        private ReportService reportService;
        private ReportType reportType;
        private DataTable dt_purchase_year;
        private DataTable dt_purchase_month;
        /// <summary>
        /// 打印参数对象
        /// </summary>
        private PrintParameter printParameter;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        private PurchaseReportControl(MainForm mainform)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.reportService = new ReportService();
            this.GenerateDataGridViewColumns();
            mainform.SetPageInfo(0, 0, 0);

            this.InitialComboBoxs();
            this.SetChartPrinter();
            this.printParameter = new PrintParameter();
            this.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// 返回ShipmentReportControl实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="reportType"></param>
        /// <returns></returns>
        public static PurchaseReportControl GetPurchaseReportControl(MainForm mainform, ReportType reportType)
        {
            if (purchaseReportControl == null)
            {
                purchaseReportControl = new PurchaseReportControl(mainform);
            }
            purchaseReportControl.reportType = reportType;

            if (reportType == ReportType.Year)
            {
                purchaseReportControl.tabControl1.SelectedIndex = 0;
                purchaseReportControl.ReportYears();
            }
            else if (reportType == ReportType.Month)
            {
                purchaseReportControl.tabControl1.SelectedIndex = 1;
                purchaseReportControl.ReportMonths();
            }
            return purchaseReportControl;
        }

        /// <summary>
        /// 初始化ComboBox
        /// </summary>
        private void InitialComboBoxs()
        {
            List<DataItem> yeararealist = new List<DataItem>();
            yeararealist.Add(DataItem.GetDataItem("最近5年", 5 + ""));
            yeararealist.Add(DataItem.GetDataItem("最近10年", 10 + ""));
            comboBox_yeararea.DataSource = yeararealist;
            comboBox_yeararea.DisplayMember = "displayMember";
            comboBox_yeararea.ValueMember = "valueMember";
            comboBox_yeararea.SelectedIndex = 0;

            DataTable dt_years = this.reportService.GetPurchaseReportAllYears();
            comboBox_years.DataSource = dt_years;
            comboBox_years.DisplayMember = "years";
            comboBox_years.ValueMember = "years";
            comboBox_years.Text = DateTime.Now.Year.ToString();
        }

        /// <summary>
        /// 报表打印机设置
        /// </summary>
        private void SetChartPrinter()
        {
            //报表打印设置
            printDocument_chart = chart1.Printing.PrintDocument;
            printDocument_chart.QueryPageSettings += new System.Drawing.Printing.QueryPageSettingsEventHandler(printDocument_chart_QueryPageSettings);
            printDocument_chart.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument_chart_PrintPage);
            printDocument_chart.EndPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_chart_EndPrint);
            printDocument_chart.PrinterSettings.DefaultPageSettings.Landscape = true;
            printPreviewDialog1.PrintPreviewControl.Zoom = 1;
        }

        #region 按时间统计

        /// <summary>
        /// 生成DataGridView列
        /// </summary>
        private void GenerateDataGridViewColumns()
        {
            this.dataGridView_year.AutoGenerateColumns = false;
            this.dataGridView_year.Columns.Clear();
            this.dataGridView_year.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("years", "年份", true, 19, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView_year.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_total", "商品金额", true, 27, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView_year.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("result", "出货金额", true, 27, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView_year.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("retotal", "退货金额", true, 27, ActKey.RIGHT, ActKey.RIGHT, true, false));

            this.dataGridView_month.AutoGenerateColumns = false;
            this.dataGridView_month.Columns.Clear();
            this.dataGridView_month.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("months", "月份", true, 19, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView_month.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_total", "商品金额", true, 27, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView_month.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("result", "出货金额", true, 27, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView_month.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("retotal", "退货金额", true, 27, ActKey.RIGHT, ActKey.RIGHT, true, false));
        }

        /// <summary>
        /// 按年统计
        /// </summary>
        public void ReportYears()
        {
            int lastLimitYears = Int32.Parse(((DataItem)comboBox_yeararea.SelectedItem).ValueMember);
            if (dt_purchase_year == null)
            {
                dt_purchase_year = this.reportService.ReportBillPurchase(0, 0, 0, lastLimitYears - 1, "years", "years");
            }
            int[] years = new int[Int32.Parse(((DataItem)comboBox_yeararea.SelectedItem).ValueMember)];
            for (int i = 0; i < years.Length; i++)
            {
                years[i] = DateTime.Now.Year - i;
            }

            this.dataGridView_year.DataSource = dt_purchase_year;
            MSChartUtil.BillChartReport(chart1, ReportType.Year, years, dt_purchase_year);
        }

        /// <summary>
        /// 按月统计
        /// </summary>
        /// <param name="years"></param>
        public void ReportMonths()
        {
            try
            {
                int years = DateTime.Now.Year;
                int[] months = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

                if (!String.IsNullOrEmpty(comboBox_years.Text.Trim()) && Regex.IsMatch(comboBox_years.Text, RegexExpress.NUMBER))
                {
                    years = Int32.Parse(comboBox_years.Text);
                }
                if (dt_purchase_month == null)
                {
                    dt_purchase_month = this.reportService.ReportBillPurchase(years, 0, 0, 0, "months", "months");
                }

                this.dataGridView_month.DataSource = dt_purchase_month;
                MSChartUtil.BillChartReport(chart1, ReportType.Month, months, dt_purchase_month);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// TabControl切换事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabControl tabControl = sender as TabControl;
            if (tabControl.SelectedIndex == 0)
            {
                this.reportType = ReportType.Year;
                this.ReportYears();
            }
            else if (tabControl.SelectedIndex == 1)
            {
                this.reportType = ReportType.Month;
                this.ReportMonths();
            }
        }

        /// <summary>
        /// 格式化单元格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.Value != null)
            {
                String typeName = e.Value.GetType().Name;
                if (typeName.Equals("Decimal"))
                    e.Value = ((decimal)e.Value).ToString("f2");
                else if (typeName.Equals("Double"))
                    e.Value = ((double)e.Value).ToString("f2");
            }
        }

        /// <summary>
        /// 按年统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_years_Click(object sender, EventArgs e)
        {
            dt_purchase_year = null;
            this.reportType = ReportType.Year;
            this.ReportYears();
        }

        /// <summary>
        /// 按月统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_months_Click(object sender, EventArgs e)
        {
            dt_purchase_month = null;
            this.reportType = ReportType.Month;
            this.ReportMonths();
        }

        #endregion

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_excel_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            String tag = button.Tag.ToString();
            if (tag.Equals("year"))
                printParameter.Dgv = dataGridView_year;
            else if (tag.Equals("month"))
                printParameter.Dgv = dataGridView_month;

            SaveFileDialog saveFileDialog = new SaveFileDialog(); 
            saveFileDialog.Filter = "导出Excel (*.xls)|*.xls"; 
            saveFileDialog.FilterIndex = 0; 
            saveFileDialog.Title = "导出文件保存路径";
            saveFileDialog.FileName = "report";

            DialogResult result = saveFileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    String chartPath = AppDomain.CurrentDomain.BaseDirectory + @"\\temp\\chart";
                    DirectoryInfo dir = new DirectoryInfo(chartPath);
                    if (!dir.Exists)
                        dir.Create();
                    chartPath += @"\\chart1.jpg";
                    chart1.SaveImage(chartPath, ChartImageFormat.Jpeg);
                    
                    string strName = saveFileDialog.FileName;
                    OfficeUtil.ExportExcel(printParameter.Dgv, strName, tabControl1.TabPages[tabControl1.SelectedIndex].Text,
                        "统计柱状图", chartPath, (float)chart1.Width, (float)chart1.Height);

                    FileInfo file = new FileInfo(chartPath);
                    if (file.Exists)
                        file.Delete();
                    MessageBox.Show("导出成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出出错！");
                    LogsUtil.Record(ex);
                }
            }
            
        }

        /// <summary>
        /// 打印DataGridView事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_dgv_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            String tag = button.Tag.ToString();
            if (tag.Equals("year"))
                printParameter.Dgv = dataGridView_year;
            else if (tag.Equals("month"))
                printParameter.Dgv = dataGridView_month;

            printPreviewDialog1.Document = printDocument_dgv;
            printPreviewDialog1.ShowDialog();
        }

        /// <summary>
        /// 打印报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_report_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument_chart;
            printPreviewDialog1.ShowDialog();
        }

        /// <summary>
        /// 打印DataGridVIew
        /// </summary>
        private void PrintDataGridView(System.Drawing.Printing.PrintPageEventArgs e)
        {
            if (printParameter.Dgv != null)
            {
                printParameter.Top = 50;
                printParameter.Left = 50;
                printParameter.RowHeight = 24;
                printParameter.IsPrintHeader = true;
                printParameter.PrintWidth = e.PageBounds.Width - 100;
                printParameter.PrintHeight = e.PageBounds.Height - 100;
                printParameter.StartRowIndex = DataGridViewPrint.PrintPages(printParameter, e);
                if (printParameter.StartRowIndex > 0)
                {
                    if (printParameter.StartRowIndex > (printParameter.Dgv.Rows.Count - 1))
                    {
                        printParameter.StartRowIndex = 0;
                    }
                }
            }
        }

        #region 打印机事件
      
        /// <summary>
        /// 打印报表
        /// 在打印每一页前发生，对于更改特定页的PageSettings十分有用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument_chart_QueryPageSettings(object sender, System.Drawing.Printing.QueryPageSettingsEventArgs e)
        {
            e.PageSettings.Landscape = true;
        }

        /// <summary>
        /// 打印报表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument_chart_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {

        }

        /// <summary>
        /// 报表打印结束事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument_chart_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {

        }

        /// <summary>
        /// 打印数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument_dgv_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            this.PrintDataGridView(e);
        }

        #endregion
    }
}
